import type { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'
import Link from 'next/link'

import styles from '../../../styles/User.module.scss'
import { useEffect, useRef, useState } from 'react'

import { Badge, Button, Divider, Ellipsis, Tag, Toast } from 'antd-mobile'

import Nav from '../../../components/Nav'
import UserNav from '../../../components/UserNav'
import Dynamic from '../../../components/UserKey/Dynamic'
import Collect from '../../../components/UserKey/Collect'
import Dingdan from '../../../components/UserKey/Dingdan'
import Followed from '../../../components/UserKey/Followed'
import Goods from '../../../components/UserKey/Goods'
import router from 'next/router'
import { BookService, DingdanService, UserService } from '../../../services'
import { IDingdan, IDynamic, IUser } from '../../../models/types'
import { Warnicon, Winicon } from '../../../components/Icon'
import { useRequest, useUpdateEffect } from 'ahooks'
import { Blist, } from '../../../services/book.service'
import { Gender, Identity, Relevance } from '../../../models/enums'
import { UList } from '../../../services/user.service'
import { advlist } from '../../../services/dingdan.service'
import Inform from '../../../components/Inform'
import { uniqueFunc } from '../../../libs/utils'

interface Props {
  keyName: string
  userinfo: IUser
  flag: boolean
  list: IDynamic[]
  dytotal: number
}

export const getServerSideProps: GetServerSideProps = async ctx => {
  const keyName = ctx.query.key
  const token = ctx.req.cookies?.token
  const id = ctx.query.id
  let user: IUser
  const res = await UserService.getuser(token ? token : '')
  // 当处于我的页面,但是未登录时候 跳到登录页
  if (id === 'mine' && res?.stat !== 'OK')
    return {
      redirect: {
        destination: '/login',
        permanent: false
      }
    }
  const flag = id === 'mine' ? true : res?.user?._id === id
  if (flag) {
    user = res?.user
  } else {
    const result = await UserService.otheruser(id as string, token ? token : '')
    user = result?.user
  }
  if (keyName === 'dynamic') {
    const dyRes = await UserService.dylist(user._id, 0, 10)
    return {
      props: {
        keyName,
        userinfo: { ...user },
        flag,
        list: dyRes.data.list,
        dytotal: dyRes.data.total
      }
    }
  }
  return {
    props: {
      keyName,
      userinfo: { ...user },
      flag,
      list: [],
      dytotal: 0
    }
  }

}

const limit = 10

const User: NextPage<Props> = ({ keyName, userinfo, flag, list, dytotal }) => {
  const [active, setActive] = useState(1)
  const [isPop, setIsPop] = useState(false)
  const [love, setLove] = useState(userinfo.islove)
  // 收藏,订单,发布
  const [books, setBooks] = useState<Blist[][]>([[], []])
  const [dylist, setDylist] = useState<IDynamic[]>(list)
  const [users, setUsers] = useState<UList[]>([])
  const [dingdans, setDingdans] = useState<IDingdan[]>([])
  const [click, setClick] = useState(0)
  const [adv, setAdv] = useState<advlist[]>([])
  const [advMore, setAdvMore] = useState(true)

  const [hasMores, setHasMores] = useState<boolean[]>([list.length < dytotal, true, true, true, true])

  function getType(n: number) {
    if (n === 2) return Relevance.Collect
    if (n === 5) return Relevance.Myissue
  }

  // 去关注
  const { data, run: dealfocus, loading } = useRequest(
    () => UserService.dealfocus(userinfo._id, !love),
    {
      manual: true,
      onSuccess: (res) => {
        if (res.stat === 'OK') setLove(!love)
        else Toast.show({ content: <Warnicon text={res.msg as string} /> })
      },
      debounceInterval: 450
    })

  // list
  const { data: userRes, run: getUsers } = useRequest(
    UserService.focuslist,
    {
      manual: true,
      onSuccess: (res) => {
        if (res.stat === 'OK') {
          const newList = res.data.list
          setUsers(oldList => {
            const arr = uniqueFunc([...oldList, ...newList]) as UserService.UList[]
            setHasMores(olds => olds.map((item, i) => i === 3 ? arr.length < res.data.total : item))
            return arr
          })
        } else setHasMores(Array(5).fill(false))
      },
    })

  const { data: blist, run: getBlist, refresh: bookRefresh } = useRequest(
    BookService.personlist,
    {
      manual: true,
      onSuccess: (res) => {
        if (res.stat === 'OK') {
          const newList = res.data.list
          if (active === 2) setBooks(oldarr => {
            if (oldarr.length === 0) {
              setHasMores(olds => olds.map((item, i) => i === 1 ? newList?.length < res.data.total : item))
              return [newList, []]
            } else {
              const arr = uniqueFunc([...oldarr[0], ...newList]) as BookService.Blist[]
              setHasMores(olds => olds.map((item, i) => i === 1 ? arr.length < res.data.total : item))
              return [arr, []]
            }
          })
          if (active === 5) {
            setBooks(oldarr => {
              if (oldarr.length === 0) {
                setHasMores(olds => olds.map((item, i) => i === 4 ? newList?.length < res.data.total : item))
                return [[], newList]
              } else {
                const arr = uniqueFunc([...oldarr[1], ...newList]) as BookService.Blist[]
                setHasMores(olds => olds.map((item, i) => i === 4 ? arr.length < res.data.total : item))
                return [[], arr]
              }
            })

          }
        } else setHasMores(Array(5).fill(false))
      },
      throttleInterval: 100
    })

  const { data: dingdanRes, run: getDingdan } = useRequest(
    DingdanService.dingdanlist,
    {
      manual: true,
      onSuccess: (res) => {
        if (res.stat === 'OK') {
          const newList = res.data.list
          if (res.stat === 'OK') setDingdans(oldList => {
            const arr = uniqueFunc([...oldList, ...newList]) as IDingdan[]
            setHasMores(olds => olds.map((item, i) => i === 2 ? arr.length < res.data.total : item))
            return arr
          });
        } else setHasMores(Array(5).fill(false))
      },
    })

  const { data: dyRes, run: getDynamics } = useRequest(
    UserService.dylist,
    {
      manual: true,
      onSuccess: (res) => {
        if (res.stat === 'OK') {
          const newList = res.data.list
          setDylist(oldList => {
            const total = oldList.length + newList.length
            setHasMores(olds => olds.map((item, i) => i === 0 ? total < res.data.total : item))
            return [...oldList, ...newList]
            // return uniqueFunc([...oldList, ...newList]) as IDynamic[]
          });
        } else setHasMores(Array(5).fill(false))
      },
    })

  const { data: infos, run: getInfos } = useRequest(
    DingdanService.sendlist,
    {
      manual: true,
      onSuccess: (res) => {
        if (res.stat === 'OK') {
          const newList = res.data.list
          setAdv(oldList => {
            const arr = uniqueFunc([...oldList, ...newList]) as DingdanService.advlist[]
            setAdvMore(arr.length < res.data.total)
            return arr
          })
        } else setAdvMore(false)
      },
    })

  useUpdateEffect(() => {
    if (active === 4) {
      getUsers(userinfo._id, 0, limit, true)
    } else if (active === 1) {
      setDylist(list)
    } else if (active === 3) {
      getDingdan(userinfo._id, 0, limit)
    } else {
      const type = getType(active) as Relevance
      getBlist(userinfo._id, type, 0, limit)
    }
  }, [active]);


  useEffect(() => {
    if (keyName === 'dynamic') setActive(1)
    if (keyName === 'collect') setActive(2)
    if (keyName === 'dingdan') setActive(3)
    if (keyName === 'followed') setActive(4)
    if (keyName === 'goods') setActive(5)
    setHasMores(Array(5).fill(true))
  }, [keyName, list])

  const userId = useRef(userinfo._id)

  useUpdateEffect(() => {
    setLove(userinfo.islove)
    if (userId.current !== userinfo._id) {
      userId.current = userinfo._id
      if (keyName === 'dynamic') setDylist([])
    }
  }, [userinfo._id])

  return (
    <div className="page">
      <Head>
        <title>{userinfo.nickname + '-用户页'}</title>
      </Head>
      <div className="wrapRaw">
        <div className={styles.header}>
          <ul className={styles.top + ' userPage'}>
            {flag && <Badge
              color='#00b578'
              content={<></>}
              style={{ '--right': '90%', '--top': '30%' }}
            >
              <li
                className={styles.new + ' iconfont icon-xiaoxi1'}
                onClick={() => {
                  setAdv([])
                  setIsPop(true)
                  getInfos(0, limit)
                  setClick(click + 1)
                }}
              ></li>
            </Badge>}
            <div className={styles.set}>
              {flag && <li
                className={styles.setc + ' iconfont icon-setup'}
                onClick={() => router.push({ pathname: '/user/pwd' })}
              >
              </li>}
              {flag && <li
                className={styles.logout}
                onClick={async () => {
                  const res = await UserService.logout()
                  if (res.stat === 'OK') {
                    Toast.show({ content: <Winicon text='登出成功' /> })
                    router.push('/login')
                  }
                }}
              >登出账号</li>
              }
            </div>
          </ul>
          <img src={userinfo.avatar} alt="" />
          <li>{userinfo.nickname}</li>
          <p>{userinfo.major[1] ? userinfo.major[1] : userinfo.major} |&nbsp;
            {
              userinfo.gender === Gender.female &&
              <i className={styles.gender + ' iconfont icon-nvxing'}></i>
            }
            {
              userinfo.gender === Gender.male &&
              <i className={styles.gender + ' iconfont icon-nanxing'}></i>
            }
            {
              userinfo.gender === Gender.null && '外星人'
            } |&nbsp;
            {userinfo.role === Identity.Official && <Tag color='success'>官方</Tag>}
            {userinfo.role === Identity.Student && <Tag color='success'>学生</Tag>}
            {userinfo.role === Identity.Admin && <Tag color='success'>管理</Tag>}
          </p>

          <div className={styles.sign}>
            <Ellipsis
              direction='end'
              rows={2}
              content={userinfo.signature}
              expandText='展开'
              collapseText='收起'
            />
          </div>
          <div className={styles.focus}>
            <div className={styles.guanzhu}>
              <li><p>{userinfo.following}</p><span>关注</span></li>
              <Divider direction='vertical' />
              <li><p>{userinfo.followers}</p><span>关注者</span></li>
              <Divider direction='vertical' />
              <li><p>{userinfo.mdb.toFixed(2)}</p><span>民大币</span></li>
            </div>
            <li>
              <Button
                onClick={() => {
                  if (flag) router.push('/user/set')
                  else dealfocus()
                }}
                loading={loading}
                size='small'
                color='success'
                fill={love ? 'solid' : 'outline'} >
                {flag ? '设置' : love ? '已关注' : '关注'}
              </Button>
            </li>
          </div>
        </div>
        <nav className={styles.nav}>
          <UserNav
            flag={flag}
            active={active}
            id={userinfo._id}
            onClick={(v: number) => { setActive(v) }}
          />
        </nav>
        <main className={styles.main}>
          {keyName === 'dynamic' &&
            <Dynamic
              dylist={dylist}
              hasMore={hasMores[0]}
              getDylist={(skip) => getDynamics(userinfo._id, skip, limit)}
            />}
          {keyName === 'collect' && flag &&
            <Collect
              books={books[0]}
              hasMore={hasMores[1]}
              getBooks={(skip) => getBlist(userinfo._id, Relevance.Collect, skip, limit)}
            />}
          {keyName === 'dingdan' && flag &&
            <Dingdan
              dingdans={dingdans}
              hasMore={hasMores[2]}
              getDingdans={(skip) => getDingdan(userinfo._id, skip, limit)}
            />}
          {keyName === 'followed' &&
            <Followed
              users={users}
              onChange={async (focus: boolean) => {
                setUsers([])
                getUsers(userinfo._id, 0, limit, focus)
              }}
              hasMore={hasMores[3]}
              getUsers={(skip, focus) => getUsers(userinfo._id, skip, limit, focus)}
            />}
          {keyName === 'goods' &&
            <Goods
              flag={flag}
              books={books[1]}
              onChange={async (type: Relevance) => {
                setBooks([books[0], []])
                await getBlist(userinfo._id, type, 0, limit)
                bookRefresh()
              }}
              hasMore={hasMores[4]}
              getBooks={(skip, type) => getBlist(userinfo._id, type, skip, limit)}
            />
          }
        </main>
      </div >

      {flag && <Inform
        click={click}
        isPop={isPop}
        setIsPop={() => setIsPop(false)}
        adv={adv}
        hasMore={advMore}
        getAdv={(skip) => getInfos(skip, limit)}
      />}
      <Nav active={flag ? 4 : 9} />
    </div >
  )
}

export default User